import { addRule, rule } from '@/services/ant-design-pro/api';
import type { ActionType, ProColumns, ProDescriptionsItemProps,FormInstance
} from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import { Button, Drawer, message } from 'antd';
import React, { useRef, useState } from 'react';
import dayjs from "dayjs";
// import type { FormValueType } from './components/UpdateForm';
/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItemD) => {
  const hide = message.loading('正在添加');
  try {
    await addRule({
      ...fields,
    });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};



const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [modaltitle,setModaltitle] = useState<string>("");
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItemD>();

  const formRef = useRef<FormInstance>()

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.RuleListItemD>[] = [
    {
      title: '工号',
      dataIndex: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'textarea',
    },
    {
      title: '当日考勤状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '请假',
          status: 'Processing',
        },
        1: {
          text: '正常',
          status: 'Success',
        },
        2: {
          text: '异常',
          status: 'Error',
        },
      },
    },
    {
      title: '打卡时间',
      dataIndex: 'updatedAt',
      valueType: 'date',
      hideInTable: true,
      initialValue: dayjs().startOf("day")

    },
    {
      title: '打卡时间',
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      hideInSearch: true,
      // renderFormItem: (item, { defaultRender, ...rest }, form) => {
      //   const status = form.getFieldValue('status');
      //   if (status === 0) {
      //     return false;
      //   }
      //   if (status === 1) {
      //     return <Input {...rest} placeholder={'请输入异常原因！'} />;
      //   }
      //   return defaultRender(item);
      // },
    },
    {
      title: '备注',
      dataIndex: 'note',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={async () => {
            await handleModalOpen(true);
            setModaltitle("编辑考勤");
            const status = options.filter( opt => opt.label === record?.status)[0].value;
            formRef.current?.setFieldsValue({...record,status});
            setCurrentRow({...record,status});
          }}
        >
          编辑
        </a>,
      ],
    },
  ];
  const options = [
    {
      label: '请假',
      value: 0,
    },
    {
      label: '正常',
      value: 1,
    },
    {
      label: '异常',
      value: 2,
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120
        }}
        // toolBarRender={() => [
        //   <Button
        //     type="primary"
        //     key="primary"
        //     onClick={() => {
        //       setModaltitle("新建考勤");
        //       formRef?.current?.resetFields();
        //       handleModalOpen(true);
        //     }}
        //   >
        //     <PlusOutlined /> 新建
        //   </Button>,
        // ]}
        request={rule}
        columns={columns}
        params={{pageSize: 10}}
      />


      <ModalForm
        title={modaltitle}
        width="400px"
        open={createModalOpen}
        formRef={formRef}
        onOpenChange={handleModalOpen}
        submitter={{
           render: (props, defaultDoms) => {
            console.log(defaultDoms)
            return [
              <Button
                type='primary'
                key="submit"
                onClick={async () => {
                formRef?.current?.validateFields();
                const o = formRef?.current?.getFieldsValue();
                const success = await handleAdd(o as API.RuleListItemD);
                if (success) {
                  formRef.current?.resetFields();
                  handleModalOpen(false);
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
                }}
              >
                确定
              </Button>,
            ];
          },
        }}
      >
        <ProFormText
          width="md"
          name="attendanceId"
          disabled
          hidden
          rules={[{ required: true}]}
        />
         <ProFormText
          width="md"
          name="id"
          label="工号"
          placeholder="请输入工号"
          disabled
          rules={[{ required: true, message: '请输入工号' }]}
        />
          <ProFormText
          width="md"
          name="name"
          label="姓名"
          disabled
          placeholder="请输入姓名"
          rules={[{ required: true, message: '请输入姓名' }]}
        />
          <ProFormSelect
          width="md"
          name="status"
          label="考勤状态"
          disabled
          placeholder="请选择考勤状态"
          rules={[{ required: true, message: '请选择考勤状态' }]}
          fieldProps={{
            options
          }}
        />
        <ProFormTextArea rules={[{ required: true, message: '请输入新增备注' }]} label={"备注"} width="md" name="note" />
      </ModalForm>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
                data: currentRow || {}
              })
            }
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default TableList;
